<template>
  <div>
    <div class="search-con search-con-top">
      <div class="fl">
        <!-- <Select v-model="searchKey" clearable class="search-col" style="width:200px">
          <Option v-for="item in columns" v-if="item.key !== 'handle'" :value="item.key" :key="`search-col-${item.key}`">{{ item.title }}</Option>
        </Select> -->
        <Input clearable placeholder="输入用户名搜索" class="search-input" v-model="condition.name"/>
        <Input clearable placeholder="输入手机号搜索" class="search-input" v-model="condition.mobile"/>
        <Button class="search-btn" type="primary" @click="List">搜索</Button>
      </div>
      <div class="fr">
        <Button class="search-btn" type="primary" @click="add">新增用户</Button>
      </div>
    </div>
    <tables ref="tables" editable :border="true" v-model="tableData" :columns="columns" :page="page" @pageSize="pageSize" @pageNum="pageNum"/>
    <Modal
        title="账户管理"
        v-model="vivisle"
        :scrollable="false"
        :closable="true"
        :mask-closable="true"
        @on-cancel="handleReset('tableItem')"
        class-name="vertical-center-modal">
        <Form ref="tableItem" :model="tableItem" :rules="ruleValidate" :label-width="80">
          <FormItem label="账号" prop="name">
              <Input v-model="tableItem.name" placeholder="请输入账号"></Input>
          </FormItem>

          <div v-if="edit">
            <FormItem label="登录密码" >
              <Input v-model="tableItem.passwd" type="password" placeholder="请输入登录密码"></Input>
            </FormItem>
          </div>
          <div v-if="!edit">
            <FormItem label="登录密码"  prop="passwd" key="passwd">
              <Input v-model="tableItem.passwd" type="password" placeholder="请输入登录密码"></Input>
            </FormItem>
          </div>

          <FormItem label="昵称" prop="nickname">
              <Input v-model="tableItem.nickname" placeholder="请输入昵称"></Input>
          </FormItem>
          <FormItem label="头像" prop="headurl">
            <div class="demo-upload-list"  v-if="tableItem.headurl">
                <img :src="tableItem.headurl">
                <div class="demo-upload-list-cover">
                    <Icon type="ios-eye-outline" @click.native="handleView(tableItem.headurl)"></Icon>
                    <Icon type="ios-trash-outline" @click.native="handleRemove()"></Icon>
                </div>
            </div>
            <Upload v-else
                ref="upload"
                :show-upload-list="false"
                :on-success="handleSuccess"
                :format="['jpg','jpeg','png']"
                :max-size="2048"
                :on-format-error="handleFormatError"
                :on-exceeded-size="handleMaxSize"
                type="drag"
                action="http://59.110.234.118:9100/uploadImgs/upload?path=admin/other"
                style="display: inline-block;width:58px;">
                <div style="width: 58px;height:58px;line-height: 58px;">
                    <Icon type="ios-camera" size="20"></Icon>
                </div>
            </Upload>
            <Modal title="图片查看" v-model="visibleImg">
                <img :src="tableItem.headurl" v-if="visibleImg" style="width: 100%">
            </Modal>
          </FormItem>
          <FormItem label="角色" prop="rid">
            <!-- :placeholder="tableItem.rname" -->
            <Select v-model="tableItem.rid" clearable  :label-in-value="true" size="large" style="width:200px" @on-change="change">
                <Option v-for="(item,index) in roleList" :value="item.rid" :key="index">{{ item.rname }}</Option>
            </Select>
          </FormItem>
          <FormItem label="启用状态">
              <i-switch size="large" :value="status" @on-change="changestatus"/>
          </FormItem>
          <FormItem label="手机号码" prop="mobile">
              <Input v-model="tableItem.mobile" placeholder="请输入手机号"></Input>
          </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" size="large" @click="handleReset('tableItem')">取消</Button>
        <Button type="primary" size="large" @click="Save('tableItem')">确定</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import Tables from "_c/tables";
import { adminD, adminS, adminL, adminQ, roleB } from "@/api/data";
export default {
  name: "Account",
  components: {
    tables: Tables
  },
  data() {
    const headerUrl = (rule, value, callback) => {
      setTimeout(res=>{
        if (this.tableItem.headurl&&this.tableItem.headurl.length>0) {
          callback();
        } else {
          callback(new Error("头像不能为空"));
        }
      },1000)
    };
    const mobileVali = (rule, value, callback) => {
      var reg = /^0?(13[0-9]|15[012356789]|18[012346789]|14[57]|17[678]|170[059]|14[57]|166|19[89])[0-9]{8}$/;
      if (reg.test(value)) {
        callback();
      } else {
        callback(new Error("请输入正确手机号"));
      }
    };
    return {
      status: false,
      vivisle: false,
      visibleImg: false,
      // id
      itemId: "",
      rid: "",
      // 详情
      tableItem: {
        name:'',
        nickname:'',
        headurl:'',
        mobile:'',
        rid:''
      },
      initPwd:'',
      // 条件
      condition: {
        pageNum: 1,
        pageSize: 10
      },
      edit:false,
      // table表头
      columns: [
        {
          type: "index",
          width: 60,
          align: "center",
          key: ""
        },
        {
          title: "头像",
          key: "headurl",
          render: (h, params) => {
            return h('img', {
              attrs: {
                src: params.row.headurl
              },
              style: {
                width: '60px',
                height: '60px',
                margin: '18px 0',
              }
            });
          }
        },
        {
          title: "昵称",
          key: "nickname"
        },
        {
          title: "账号",
          key: "name"
        },
        {
          title: "角色名称",
          key: "rname"
        },
        {
          title: "手机号码",
          key: "mobile"
        },
        {
          title: "操作",
          key: "handle",
          // minWidth:150,
          // options: ['delete','delete'],
          button: [
            (h, params, vm) => {
              return [
                h(
                  "Button",
                  {
                    props: {
                      type: "primary",
                      size: "small"
                    },
                    style: {
                      marginRight: "5px",
                      marginBottom: "5px",
                      display: params.row.aid==='ea7e0066629e4ae889a91fb4726baa49' ? "none" : 'inline-block'
                    },
                    on: {
                      click: () => {
                        this.itemId = params.row.aid;
                        let item = JSON.parse(JSON.stringify(params.row))
                        delete item.initRowIndex
                        delete item._index
                        delete item._rowKey
                        this.tableItem = item
                        this.$set(this,'status',item.status == 1)
                        this.initPwd = item.passwd
                        this.edit = true
                        this.vivisle = true;
                        // this.Query();
                      }
                    }
                  },
                  "编辑"
                )
              ];
            },
            (h, params, vm) => {
              return h(
                "Poptip",
                {
                  props: {
                    confirm: true,
                    title: "你确定要删除吗?"
                  },
                  on: {
                    "on-ok": () => {
                      this.itemId = params.row.aid;
                      this.Delete();
                    }
                  }
                },
                [
                  h(
                    "Button",
                    {
                      props: {
                        type: "error",
                        size: "small"
                      },
                      style: {
                        marginRight: "5px",
                        display: params.row.aid==='ea7e0066629e4ae889a91fb4726baa49' ? "none" : 'inline-block',
                      marginBottom: "5px"
                      }
                    },
                    "删除"
                  )
                ]
              );
            }
          ]
        }
      ],
      // table数据
      tableData: [],
      roleList: [],
      // 分页数据
      page: {
        current: 1,
        total: 0,
        pageSize: 10
      },
      ruleValidate: {
        name: [
          {
            required: true,
            message: "账号不能为空",
            trigger: "blur"
          }
        ],
        nickname: [
          {
            required: true,
            message: "昵称不能为空",
            trigger: "blur"
          }
        ],
        headurl: [{ required: true, validator: headerUrl, trigger: "change,blur" }],
        rid: [
          {
            required: true,
            message: "请选择相应角色",
            trigger: "change"
          }
        ],
        rname: [
          {
            required: true,
            message: "请选择相应角色",
            trigger: "change"
          }
        ],
        mobile: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {validator: mobileVali, trigger: "blur"}
        ],
        passwd: [
          {
            required: true,
            message: "请填写登录密码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  mounted() {
    this.List();
    this.ListRole();
    let id = sessionStorage.getItem('id')
  },
  methods: {
    add(){
      this.edit = false
      this.vivisle = true
      this.status = true
    },
    handleReset (name) {
      this.vivisle = false
      this.$refs[name].resetFields();
      this.tableItem.passwd = ''
      this.$set(this,'status',false)
      // this.tableItem = {}
    },
    pageSize(value) {
      this.condition.pageSize = value
      this.condition.pageNum = 1
      this.List()
    },
    pageNum(value) {
      this.condition.pageNum = value
      this.List()
    },
    change (item) {
    },
    handleView() {
      this.visibleImg = true;
    },
    handleRemove() {
      this.tableItem.headurl = "";
    },
    handleSuccess(res, file) {
      this.$set(this.tableItem,'headurl',res.data)
      this.tableItem.headurl = res.data;
    },
    handleFormatError(file) {
      this.$Notice.warning({
        title: ""
      });
    },
    handleMaxSize(file) {
      this.$Notice.warning({
        title: "文件超出2M范围"
      });
    },
    // 分页数据获取
    List() {
      adminL(this.condition).then(res => {
        if (res.code==1) {
        let { data, total } = res.data;
        this.tableData = data;
        this.page.total = total;
        }
      });
    },
    ListRole() {
      roleB().then(res => {
        if (res.code==1) {
          this.roleList = res.data;
        }
      });
    },
    // 详情数据获取
    Query() {
      adminQ({ id: this.itemId }).then(res => {
        if (res.code==1) {
        // res.data.status = res.data.status != 2 ? true : false;
        this.tableItem = res.data;
        this.status = res.data.status == 1
        // this.tableItem.rname = "商户"
        this.vivisle = true;
        }
      });
    },
    // 保存
    Save(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          var obj = JSON.parse(JSON.stringify(this.tableItem))
          obj.status = this.status == true ? 1 : 2
          delete obj.rname
          if(this.edit && obj.passwd && obj.passwd == this.initPwd ){
              obj.passwd = ''
               delete obj.passwd
          }
          adminS(obj).then(res => {
            if (res.code === 1) {
              this.$refs[name].resetFields();
              // this.tableItem = {};
              this.vivisle = false
              this.List();
            }
          });
        }
      });

    },
    changestatus (status1) {
        // this.$Message.info('开关状态：' + status1);
        this.$set(this,'status',status1)
        // this.$Message.info('------------' + this.status);
    },
    // 删除
    Delete() {
      adminD({ id: this.itemId }).then(res => {
        if (res.code === 1) {
          this.itemId = "";
          this.List();
        }
      });
    }
  }
};
</script>
